function LayerMember() {
  this.DEFAULT = {
    size: { width: 480, height: 640 },
    close: true,
    mask: true,
    maskClose: true
  }
  this.config = null
  this.init()
}

// 原型链
LayerMember.prototype = {
  /**
   * loadjs 同步或异步方式加载js文件 opt:
   * @param  {[type]} src 加载js地址
   * @param  {[type]} opt  {charset,id,data,async:true} 默认同步输出
   */
  loadjs: function (src, opt) {
    var doc = document;
    var isFlag = false;
    var script = Array.prototype.slice.call(doc.getElementsByTagName('script'), 0);
    script.forEach(function(item){
      if (item.src === src){
        isFlag = true
      }
    });
    if (isFlag) {
      return false
    }
    opt = opt || {};
    if (opt.async) {
      var obj = doc.createElement('script');
      obj.src = src;
      obj.async = true;
      obj.type = 'text/javascript';
      if (opt.charset) {
        obj.charset = opt.charset;
      }
      if (opt.data) {
        obj.data = opt.data;
      }
      if (opt.id) {
        obj.id = opt.id;
      }
      (doc.head || doc.getElementsByTagName('head')[0] || doc.docElement).appendChild(obj);
    } else {
      doc.write('<script src="' + src + '"' + (opt.charset ? ' charset="' + opt.charset + '"' : '') + (opt.data ? ' data="' + opt.data + '"' : '') + (opt.id ? ' id="' + opt.id + '"' : '') + '></script>');
    }
  },
  init: function() {
    // 创建公共样式
    this.createStyle()
    this.loadjs('http://static.321mh.com/js/clipboard.min.js', { async: true });
  },

  // 显隐body滚动
  overflowHandle: function(flag) {
    var obj = flag ?
      { 'overflow': 'hidden', height: $(window).height() + 'px' } :
      { 'overflow': 'auto', height: 'auto' }

    $('body').css(obj)
  },

  // 创建显示DOM
  createHtml: function(config) {
    var opt = this.config = $.extend({}, this.DEFAULT, config, this.getSchemeConfig())
    $mhMember = $('#mh_member')
    var size = opt.size,
      maskStr

    if($mhMember.length) return

    if(opt.mask) {
      maskStr = '<div class="mh_member_mask"' + (opt.maskClose ? '' : ' style="pointer-events:none;"') + '></div>'
    }
    var str = '<div id="mh_member"><div class="mh_member_layer" style="width:' + size.width + 'px;height:' + size.height + 'px;margin:-' + size.height / 2 + 'px 0 0 -' + size.width / 2 + 'px;"><span class="mh_member_close">&times;</span><div class="mh_member_bd"><img src="' + opt.src + '" onclick="layerM.schemeHandle()"></div></div>' + maskStr + '</div>'

    $('body').append(str)

    this.overflowHandle(true)
    this.bindEvent()
  },

  // 创建样式
  createStyle: function() {
    if($('#mh_member_style').length) return
    $('head').append('<style id="mh_member_style">.mh_member_layer{position:fixed;top:50%;left:50%;z-index:9999;text-align:center;background:#fff;}.mh_member_layer>.mh_member_bd{vertical-align:top;}.mh_member_bd img{width:100%;}.mh_member_close{font-family:serif;font-size:24px;display:block;width:32px;height:32px;position:absolute;top:0;right:0;line-height:30px;text-align:center;background:#000;opacity:0.5;color:#fff;border-bottom-left-radius:8px;cursor:pointer;}.mh_member_mask{background:#000;opacity:0.75;position:fixed;left:0;top:0;bottom:0;right:0;z-index:9998;}</style>')
  },

  // 关闭dom
  closeDom: function() {
    $('#mh_member').remove()
    this.overflowHandle()
    location.href = location.href.substr(0, location.href.lastIndexOf('/')+1)
  },

  bindEvent: function() {
    var _this = this
    if(_this.config.close) {
      $('body').on('click', '.mh_member_close', function() {
        _this.closeDom()
      })
    }
    if(_this.config.maskClose) {
      $('body').on('click', '.mh_member_mask', function() {
        _this.closeDom()
      })
    }
  },

  creatIframe: function(src) {
    // 如果用户已经安装了应用 抛出schemes,打开app对应页面
    var ifr = document.createElement('iframe');
    ifr.style.display = 'none';
    ifr.src = src;
    document.body.appendChild(ifr);
  },
  _deviceGPU: function(){
    var canvas = document.createElement('canvas'),
    gl = canvas.getContext('experimental-webgl'),
    debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
    return (gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) || '');
  },
  _copyToClipboard: function (schemeAdr) {
    // 添加剪切板拷贝功能
    var body = document.getElementsByTagName('body')[0];
    if (!/km-app/.test(body.className) && body.className){
      body.className += ' km-app';
    }else{
      body.className = 'km-app';
    }
    body.setAttribute('data-schemes', schemeAdr)
    Clipboard && new Clipboard('.km-app', {
      text: function (trigger) {
        return trigger.getAttribute('data-schemes');
      }
    })
  },
  schemeHandle: function() {
    var _this = this;
    var config = _this.config;
    var UA = navigator.userAgent.toLowerCase();
    var schemeAdr = config.scheme_Adr;
    this._copyToClipboard(schemeAdr)
    // var deviceGPU = _this._deviceGPU();
    if(UA.match(/(iPhone|iPod|iPad);?/i)) {
      //抛出schemes,打开app对应页面
      // for(var i = 0; i < schemeAdr.length; i++) {
      window.location.href = schemeAdr;
      //}
      //由于部分ios中打开app后，WAP页面会被挂起，定时器不会被执行。因此可以做下优化：
      //WAP页重新被聚焦后，如果超过1s，认为APP被打开了，重新聚焦时就不必再跳转到APP下载页
      var startTime = Date.now();
      var delayTime = /safari/.test(UA) ? 3000 : 1000;
      var timer = setInterval(function() {
        var endTime = Date.now();
        if(endTime - startTime > delayTime) {
          clearInterval(timer);
          window.location.href = config.iosurl || config.url;
        }
      }, 25);
    } else {
      // 更改andriod兼容两张方式打开
      // for(var i = 0; i < schemeAdr.length; i++) {
      //   _this.creatIframe(schemeAdr[i]);
      // }
      _this.creatIframe(schemeAdr);
      //跳转下载页
      setTimeout(function() {
        window.location.href = config.url;
      }, 600);
    }
  },
  getHost: function() {
    let host = location.host.replace(/([a-z]{1,6}\.)?(.+)(\.[a-z]{2,4})(\:\d+)?$/, '$2');
    if (/localhost|(\d{1,3}.){3}\d{1,3}/.test(host)) {
      host = 'kanman'
    } 
    return host
  },

  getScheme: function(data) {
    var gobalInfo = window.gobal_info || {}; // 从文档中获取gobal_info
    var comic_id = gobalInfo.comic_id || '';
    var UA = navigator.userAgent.toLowerCase();
    // if (UA.match(/(iPhone|iPod|iPad);?/i)) {
    // data.scheme_Adr = 'tkanmanapp' // 将所有的导流到看漫画
    // }
    return data.scheme_Adr + '://' + location.hostname.replace('m.', 'www.') + '/open?id=' + (comic_id ? comic_id : '');
    // return [
    //   data.scheme_Adr + '://' + location.hostname.replace('m.', 'www.') + '/open?id=' + comic_id,
    //   data.scheme_Adr + '://goto?page=' + (comic_id ? 'dir' : 'index') + '&comic_id=' + comic_id
    // ];
  },
  getSchemeConfig: function() {
    var options = schemeConfig
    var host = this.getHost(); // 获得host

    if (host === 'kanman') host = 'iyouman'

    var data = options[host];
    data['host'] = host; // 设置host的值
    
    return $.extend(data, {
      url: 'http://a.app.qq.com/o/simple.jsp?pkgname=' + data.pkgname + '&ckey=' + data.ckey,
      // iosurl: 'https://itunes.apple.com/app/apple-store/' + data.ios,
      scheme_Adr: this.getScheme(data),
      src: data.src
    });
  }
}
var schemeConfig = {
  kanman: {
    ckey: 'CK1382108356199', // 看漫画微下载: CK1382108356199
    ios: 'id1303470988', // 看漫画IOS: id1303470988
    appname: '看漫画',
    pkgname: 'com.wbxm.icartoon',
    scheme_Adr: 'tkanmanapp',
    src: 'http://image.mhxk.com/file/global/'+ (isMobile?'guide-kmh.png':'pc-1.png')
  },
  iyouman: {
    ckey: 'CK1383325844989', // 爱优漫微下载: CK1383325844989
    ios: 'id1344658366', // 爱优漫IOS: id1344658366
    appname: '爱优漫',
    pkgname: 'com.comic.iyouman',
    scheme_Adr: 'tiyoumanapp',
    src: 'http://image.mhxk.com/file/global/'+ (isMobile?'guide-iym.png':'pc-1.png')
  },
  shenmanhua: {
    ckey: 'CK1383322645544', // 神漫画微下载: CK1383322645544
    ios: 'id1342099056', // 神漫画IOS:id1342099056
    appname: '神漫画',
    pkgname: 'com.comic.shenmanhua',
    scheme_Adr: 'tshenmanhuaapp',
    src: 'http://image.mhxk.com/file/global/' + (isMobile ?'guide-smh.png':'pc-1.png')
  },
  isaman: {
    ckey: 'CK1383328534446', // 爱飒漫画
    ios: 'id1344659342', //爱飒漫画ISO: id1344659342
    appname: '爱飒漫画',
    pkgname: 'com.comic.isaman',
    scheme_Adr: 'tisamanapp',
    src: 'http://image.mhxk.com/file/global/' + (isMobile ? 'guide-ismh.png' : 'pc-1.png')
  },
  douluodalu3: {
    ckey: 'CK138297596322', // 漫画台: CK138297596322
    ios: 'id1243372811', // 漫画台IOS:id1243372811
    appname: '漫画台',
    pkgname: 'com.comic.manhuatai',
    scheme_Adr: 'tmanhuataiapp',
    src: 'http://image.mhxk.com/file/global/' + (isMobile ?'guide-dldl3.png':'pc-1.png')
  },
  manhuatai: {
    ckey: 'CK138297596322', // 漫画台微下载: CK138297596322
    ios: 'id1243372811', // 漫画台IOS: id1243372811
    appname: '漫画台',
    pkgname: 'com.comic.manhuatai',
    scheme_Adr: 'tmanhuataiapp',
    src: 'http://image.mhxk.com/file/global/' + (isMobile ?'guide-mht.png':'pc-1.png')
  },
  // zymk: {
  //   ckey: 'CK1353950509167', // 知音漫客微下载: CK1353950509167
  //   ios: 'id1012491820', // 知音漫客IOS: id1012491820
  //   appname: '知音漫客',
  //   pkgname: 'cn.zymk.comic',
  //   scheme_Adr: 'zymkapp',
  //   src: 'http://image.mhxk.com/file/global/'+ (isMobile?'h5-1.png':'pc-1.png')
  // }
}

// 通过价格决定是否显示
var hasLayerMember = false
var layerM = new LayerMember()
function showLayerMember() {
  var isFlag = mh_info && mh_info.price > 0 && __cr && __cr.thispage && __cr.thispage > 1
  if (isFlag && !hasLayerMember) {
    if (isMobile) {
      layerM.createHtml({ maskClose: true, size: { width: 300, height: 400 } })
    } else {
      layerM.createHtml({ maskClose: true, size: { width: 600, height: 400 } })
    }
    hasLayerMember = true
  }
}
showLayerMember()
$(window).scroll(function() {
  showLayerMember()
})